<!-- 文章列表展示 -->
<template>
  <div class="article-container" ref="article-list">
    <van-list
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      error-text="请求失败，点击重新加载"
    >
      <template #finished>
        <div @click="onRefresh">尝试加载更多~</div>
      </template>
      <van-pull-refresh
        v-model="isPullLoading"
        success-text="刷新成功"
        @refresh="onRefresh"
      >
        <van-cell-group inset>
          <van-cell v-for="article in articles" :key="article.id">
            <template #title>
              <ArticleItem :article="article" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-pull-refresh>
    </van-list>
  </div>
</template>

<script>
import { getArticle } from "@/api/article.js";
import ArticleItem from "@/components/article-item/index.vue";
import { debounce } from "loadsh";

export default {
  name: "ArticleList",
  props: ["channel"],
  data() {
    return {
      articles: [],
      loading: false,
      finished: false,
      timestamp: null,
      isPullLoading: true,
      ArticleListDom: null,
      scrollTop: 0,
    };
  },
  methods: {
    async onLoad() {
      const { data } = await getArticle({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1,
      });
      let { results } = data.data;
      this.articles.push(...results);

      // 设置本次加载状态
      this.loading = false;
      this.isPullLoading = false;
      // 数据加载完成
      if (results.length) this.timestamp = data.data.pre_timestamp;
      else this.finished = true;
    },

    /* 下拉刷新 */
    async onRefresh() {
      this.finished = false;
      const { data } = await getArticle({
        channel_id: this.channel.id,
        timestamp: Date.now(),
        with_top: 1,
      });
      this.articles.unshift(...data.data.results);
      this.isPullLoading = false;
    },
    // debounce需要使用对象的方式进行调用才生效
    changeScrollTop: debounce(function () {
      this.$nextTick(() => {
        this.scrollTop = this.ArticleListDom.scrollTop;
      });
    }, 300),
  },
  components: {
    ArticleItem,
  },
  mounted() {
    this.ArticleListDom = this.$refs["article-list"];
    this.ArticleListDom.onscroll = () => {
      this.changeScrollTop();
    };
  },
  activated() {
    this.ArticleListDom.scrollTop = this.scrollTop;
  },
};
</script>

<style lang="less" scoped>
.article-container {
  position: fixed;
  left: 0;
  right: 0;
  top: 90px;
  bottom: 50px;
  overflow-y: auto;
  .van-list {
    position: relative;
    left: 0;
    right: 0;
    bottom: 50px;
    top: 0;
  }
  /deep/.van-cell-group--inset {
    margin: 2px 5px;
  }
}
</style>